﻿using System;
using System.Threading;
using XcoAppSpaces.Contracts.Logging;
using XcoAppSpaces.Transport.WCF;
using NUnit.Framework;
using XcoAppSpaces.Contracts.Transport;
using XcoAppSpaces.Serialization.Binary;

namespace test.XcoAppSpaces.Transport.WCF.wshttp
{
	[TestFixture]
	public class testXcoWCFTransportService
	{
        private XcoBinarySerializer serializer = new XcoBinarySerializer();
        private ReceivedTmp recv1;
        private ReceivedTmp recv2 ;
	

		[SetUp]
		public void SetUp()
		{
            recv1 = new ReceivedTmp();
            recv2 = new ReceivedTmp();
			XcoLoggerFactory.CreateInstance = (t => new ConsoleLogger());
		}


        /*
         HowTo: Examle for Testing with www.xvsmtest.com             
         1) Create self signed certificate (certification authority)
                 makecert -n "CN=xvsmCA" -r -sv xvsmCA.pvk xvsmCa.cer
         2) Import the certificate to the trusted "Trusted Root Certification Authorities"
         3) Create certificate
                makecert -sk www.xvsmtest.com -iv xvsmCA.pvk -n "CN=www.xvsmtest.com" -ic xvsmCA.cer -sr localmachine -ss my -sky exchange -pe www.xvsmtest.com.cer 
         4) Add testdomain to the hosts file ( %windows%\System32\drivers\etc\hosts)
                add line: 127.0.0.1 	www.xvsmtest.com
         */

        [Test]
		public void Connect()
		{
            recv1.WaitForStop = new ManualResetEvent(false);
            recv2.WaitForStop = new ManualResetEvent(false);
            using (XcoWCFTransportService wcf1 = new XcoWCFTransportService("http://www.xvsmtest.com:8123"))
			{
                using (XcoWCFTransportService wcf2 = new XcoWCFTransportService("http://www.xvsmtest.com:8124"))
				{
					wcf1.OnMessageReceived += recv1.MessageReceived;
					wcf2.OnMessageReceived += recv2.MessageReceived;
					
					wcf1.Start();
					wcf2.Start();

                    byte[] data = serializer.Serialize(new IntMsg { value = 5 });
                    byte[] data2 = serializer.Serialize(new IntMsg { value = 3 });

                    wcf2.Send(new XcoMessage { Content = data }, wcf1.LocalAddress);
					wcf1.Send(new XcoMessage { Content = data2 }, wcf2.LocalAddress);

                    recv1.WaitForStop.WaitOne(1000);
                    recv2.WaitForStop.WaitOne(1000);

					wcf1.Stop();
					wcf2.Stop();
                    Assert.AreEqual(recv1.Sum, 5);
                    Assert.AreEqual(recv2.Sum, 3);
					
				}
			}
		}

		
	}


}
